import storejs from '@/utils/storejs';
import {userKeys, hasLogin} from '@/utils/authUtils.js';
import API from '@/api/index.js';

const keys = userKeys;

// 用户状态
const state = {
    //token信息
    tokenInfo: storejs.get(keys.tokenInfo),
    //当前token字符串
    token: storejs.get(keys.token),
    //用户信息
    userInfo: storejs.get(keys.userInfo),
}


const getters = {

}

const mutations = {
    setTokenInfo(state, tokenInfo){
		// token值
        let token = tokenInfo.accessToken;
        state.tokenInfo = tokenInfo;
        state.token = token;

        // 保存到本地
        storejs.set(keys.token, token);
        storejs.set(keys.tokenInfo, tokenInfo);
    },
    setUserInfo(state, userInfo){
        state.userInfo = userInfo;
        storejs.set(keys.userInfo, userInfo);
    },
}

const actions = {
    /**
     * 登录
     */
    login(context, formData){
		console.log("context", context);
        return new Promise((resolve, reject)=>{
			API.user.login(formData).then(res=>{
				// 存储至本地
				let data = res.data;
				let userInfo = data.userInfo;
				let tokenInfo = data.tokenInfo;
				context.commit('setUserInfo', userInfo);
				context.commit('setTokenInfo', tokenInfo);
				
				resolve(res);
			}).catch(e=>{
				reject(e);
			});
		});
    },
    /**
     * 注销登录
     */
    logout(context){
       return new Promise((resolve, reject)=>{
		   console.log("注销登录")
		   logout(context);
		   resolve();
	   });
    },
    /**
     * 获取个人信息
     */
    getUserInfo(context){
        
    },
};

/**
 * 注销登录
 * @param context state上下文
 */
function logout(context) {
    // 清除缓存
    storejs.remove(keys.token);
    storejs.remove(keys.tokenInfo);
    storejs.remove(keys.userInfo);

    if (context) {
        context.state.token = null;
        context.state.tokenInfo = null;
        context.state.userInfo = null;
    }
}

export default {
    namespaced: true,
    state,
    getters,
    mutations,
    actions
}
